"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import Input from "@/components/custom-ui/input";
import { Loader } from "lucide-react";
import { UpdateProfileFormData, UpdateProfileSchema } from "@/schemas/profile";
import { useMutation } from "@tanstack/react-query";
import { UpdateProfileAction } from "@/actions/profile";
import { useEffect } from "react";
import { User } from "../../../../../generated/prisma/client";
import { useSession } from "next-auth/react";
import { regions } from "@/lib/region";
import { Select } from "@/components/custom-ui/select";
import { useTranslations } from "next-intl";

export default function ProfileForm({
  data,
  fileId,
}: {
  data: Omit<User, "password"> | null | undefined;
  fileId: string;
}) {
  const t = useTranslations("profilePages");
  const tZod = useTranslations("zod");
  const { update } = useSession();
  const form = useForm<UpdateProfileFormData>({
    resolver: zodResolver(UpdateProfileSchema(tZod)),
    defaultValues: {
      id: "",
      name: "",
      first_name: "",
      last_name: "",
      mobile: "",
      region: "",
      address: "",
      image: "",
    },
  });

  useEffect(() => {
    if (data) {
      form.reset({
        id: data.id ?? "",
        name: data.name ?? "",
        first_name: data.first_name ?? "",
        last_name: data.last_name ?? "",
        mobile: data.mobile ?? "",
        region: data.region ?? "",
        address: data.address ?? "",
        image: data.image ?? "",
      });
    }
  }, [data, form]);

  useEffect(() => {
    if (fileId) {
      form.setValue("image", fileId);
    }
  }, [fileId, form]);

  const mutation = useMutation({
    mutationFn: UpdateProfileAction,
    onSuccess: (data) => {
      if (data.success) {
        toast.success(data.success);
      }
      if (data.error) {
        toast.error(data.error);
      }
    },
    onError: (error) => {
      toast.error(error.message);
    },
  });

  const onSubmit = async (values: UpdateProfileFormData) => {
    const r = await mutation.mutateAsync(values);
    if (r.success) {
      await update({ name: values.name, image: values.image });
    }
  };
  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="w-full space-y-6">
        <div className="flex flex-col sm:flex-row gap-4">
          <FormField
            control={form.control}
            name="name"
            render={({ field }) => (
              <FormItem className="w-full">
                <FormLabel className="text-muted-foreground">{t("name")}</FormLabel>
                <FormControl>
                  <Input placeholder="example" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="mobile"
            render={({ field }) => (
              <FormItem className="w-full">
                <FormLabel className="text-muted-foreground">{t("mobile")}</FormLabel>
                <FormControl>
                  <Input placeholder="15100000000" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
        </div>
        <div className="flex flex-col md:flex-row gap-4">
          <FormField
            control={form.control}
            name="first_name"
            render={({ field }) => (
              <FormItem className="w-full">
                <FormLabel className="text-muted-foreground">{t("firstName")}</FormLabel>
                <FormControl>
                  <Input placeholder="example" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="last_name"
            render={({ field }) => (
              <FormItem className="w-full">
                <FormLabel className="text-muted-foreground">{t("lastName")}</FormLabel>
                <FormControl>
                  <Input placeholder="example" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
        </div>
        <Select label={t("countryOrRegion")} name="region" options={regions} />
        <FormField
          control={form.control}
          name="address"
          render={({ field }) => (
            <FormItem>
              <FormLabel className="text-muted-foreground">{t("address")}</FormLabel>
              <FormControl>
                <Input placeholder="address" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <Button
          className="w-full h-12 cursor-pointer select-none"
          type="submit"
          disabled={mutation.isPending}
        >
          {mutation.isPending ? <Loader className="animate-spin" /> : null}
          {t("updateProfile")}
        </Button>
      </form>
    </Form>
  );
}
